const vscode = require('vscode');
const util = require('../util');

/**
 * 鼠标悬停提示
 * @param {*} document 
 * @param {*} position 
 * @param {*} token 
 */
function provideHover(document, position, token) {
    const word        = document.getText(document.getWordRangeAtPosition(position));
    const line        = document.lineAt(position);
    const projectPath = util.getProjectPath(document);

    const result = /((^|=| )\w+\.proxy\.)(\w+?)\.(\w+?)($|\(| )/g.exec(line.text);
    if (!result) return;
    // 如果匹配到 this.proxy.xxx
    if(result[3] == word) {
        const matchStart = result.index + result[1].length;
        const matchEnd = matchStart + word.length;
        // 确认匹配的字符串就是当前光标所在的字符串
        if(position.character >= matchStart && position.character <= matchEnd) {
            const serviceName =  util.upperFirstLetter(word); // 首字母大写
            const proxy = require(`${projectPath}/config/proxy.js`);
            const services = proxy.services.filter(item => !!item.api[serviceName]);
            util.log(services);
            if (services.length) {
                // 一般来说这种情况不存在
                if (services.length > 1) {
                    util.log('匹配到多个services，默认进入第一个！');
                }
                const api = services[0].api[serviceName];
                // hover内容支持markdown
                return new vscode.Hover(`* **包名**：${api.interfaceName}\n* **组别**：${api.group}`);
            }
        }
    }
}

module.exports = function(context) {
    // 注册鼠标悬停提示
    context.subscriptions.push(vscode.languages.registerHoverProvider('javascript', {
        provideHover
    }));
};